import os
import random
import tkinter as tk
from tkinter import ttk, filedialog, messagebox
import threading
import pandas as pd
import json
import time

from 获取单元信息 import get_unit_detail, open_account_palt_form
from 更改单元信息 import update_intelligent_expansion, update_device_price


class IntelligentExpansionGUI:
    def __init__(self, root):
        self.root = root
        self.root.title("部分单元信息设置工具")
        self.root.geometry("800x600")
        self.root.configure(bg="#f5f5f5")

        # 初始化变量
        self.file_path = tk.StringVar()
        self.log_callback = None
        self.unit_data = None

        self.create_widgets()

    def create_widgets(self):
        style = ttk.Style()
        style.theme_use('clam')

        # 样式配置
        style.configure('TFrame', background='#f5f5f5')
        style.configure('TLabel', background='#f5f5f5', font=('Segoe UI', 9))
        style.configure('TButton', font=('Segoe UI', 9), padding=6)
        style.configure('TEntry', font=('Segoe UI', 9), padding=5)

        style.map('primary.TButton',
                  foreground=[('active', 'white'), ('!active', 'white')],
                  background=[('active', '#45a049'), ('!active', '#4CAF50')])
        style.map('danger.TButton',
                  foreground=[('active', 'white'), ('!active', 'white')],
                  background=[('active', '#d32f2f'), ('!active', '#f44336')])

        main_frame = ttk.Frame(self.root, padding="10")
        main_frame.pack(fill=tk.BOTH, expand=True)

        # ===== 子账号ID区域 =====
        account_frame = ttk.Frame(main_frame)  # 新建一个专门放置账号ID的框架
        account_frame.pack(fill=tk.X, pady=(0, 5))  # 放在最上面

        ttk.Label(account_frame, text="子账号ID:").pack(side=tk.LEFT, padx=(0, 5))
        self.account_entry = ttk.Entry(account_frame, width=30)
        self.account_entry.insert(0, "")  # 默认空值
        self.account_entry.pack(side=tk.LEFT, padx=5)

        # ===== 文件选择区域 =====
        file_frame = ttk.LabelFrame(main_frame, text="", padding=(15, 10))
        file_frame.pack(fill=tk.X, pady=(0, 5))  # 放在账号ID下方

        ttk.Button(file_frame, text="选择Excel文件", command=self.select_file).pack(side=tk.LEFT, padx=5)
        ttk.Entry(file_frame, textvariable=self.file_path, width=50).pack(side=tk.LEFT, padx=10)
        self.start_button = ttk.Button(file_frame, text="▶ 开始执行", command=self.start_task, style='primary.TButton')
        self.start_button.pack(side=tk.LEFT)

        # ===== 日志区域 =====
        log_frame = ttk.LabelFrame(main_frame, text="操作日志", padding=(10, 5))
        log_frame.pack(fill=tk.BOTH, expand=True, pady=5)

        self.log_text = tk.Text(log_frame, wrap=tk.WORD, bg='white', height=20, font=('Consolas', 9))
        self.log_text.pack(fill=tk.BOTH, expand=True)
        self.log_text.config(state=tk.DISABLED)

        scrollbar = ttk.Scrollbar(log_frame, orient="vertical", command=self.log_text.yview)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        self.log_text.config(yscrollcommand=scrollbar.set)

        # ===== 状态栏 =====
        status_bar = ttk.Frame(self.root, relief=tk.SUNKEN)
        status_bar.pack(fill=tk.X, pady=(5, 0))

        self.status_label = ttk.Label(status_bar, text="就绪", foreground="green")
        self.status_label.pack(side=tk.LEFT, padx=5)

    def select_file(self):
        file_path = filedialog.askopenfilename(title="选择Excel文件", filetypes=[("Excel 文件", "*.xlsx *.xls")])
        if file_path:
            self.file_path.set(file_path)
            self.status_label.config(text="✅ 文件已选择", foreground="blue")

    def start_task(self):
        file_path = self.file_path.get()
        if not file_path or not os.path.exists(file_path):
            messagebox.showwarning("警告", "请先选择有效的Excel文件")
            return

        try:
            self.account_id = self.account_entry.get().strip()
            if not self.account_id:
                self.log_message("请输入账号ID！", "red")
                self.status_label.config(text="需要账号ID", foreground="red")
                return

            df = pd.read_excel(file_path)
            unit_ids = df['单元ID'].astype(int).tolist()
            intelligent_values = df['智能扩量'].apply(lambda x: int(x) if pd.notna(x) else None).tolist()
            device_price_list = df['手机价格'].apply(lambda x: str(x).strip().split('\n') if pd.notna(x) else []).tolist()
            self.unit_data = list(zip(unit_ids, intelligent_values, device_price_list))

            self.status_label.config(text="🔄 正在处理...", foreground="orange")

            thread = threading.Thread(target=self.process_units, daemon=True)
            thread.start()

        except Exception as e:
            messagebox.showerror("错误", f"读取Excel失败: {str(e)}")
            self.status_label.config(text="❌ 数据加载失败", foreground="red")

    def process_units(self):
        self.log_message(f"⚠️ 正在打开合作伙伴平台", "green")
        unit_dict_cookie = open_account_palt_form(self.account_id)
        num_count = len(self.unit_data)
        index = 0

        for unit_id, value, device_price_list in self.unit_data:
            index += 1
            self.log_message(f"正在处理第{index}/{num_count}条信息..", "blue")

            try:
                # 更新智能扩量值（如果Excel有提供）
                if value is not None:
                    status = "未指定" if value is None else ("开启" if value == 1 else "关闭")
                    self.log_message(f"🔧 处理单元ID: {unit_id}, 智能扩量状态: {status} ", "blue")
                    raw_data = get_unit_detail(unit_id, self.account_id, unit_dict_cookie)
                    if not raw_data:
                        self.log_message(f"⚠️ 单元ID {unit_id} 获取详情失败", "red")
                        continue

                    target_config = raw_data.get('targetConfig', {})
                    target_config['intelligentExpansion'] = value
                    self.log_message(f"📝 替换智能扩量值为: {value}", "blue")
                    result = update_intelligent_expansion(raw_data, value, unit_dict_cookie, self.account_id)
                    self.result_status(result, unit_id)
                    time.sleep(random.randint(1, 3))

                # 更新手机价格（如果Excel有提供）
                if device_price_list is not None:
                    self.log_message(f"🔧 处理单元ID: {unit_id}, 手机价格修改为: {'未指定' if not device_price_list else device_price_list}", "blue")
                    raw_data = get_unit_detail(unit_id, self.account_id, unit_dict_cookie)
                    if not raw_data:
                        self.log_message(f"⚠️ 单元ID {unit_id} 获取详情失败", "red")
                        continue

                    device_price_str = '#'.join(device_price_list)
                    target_config = raw_data.get('targetConfig', {})
                    target_config['targetDevicePrice'] = device_price_str

                    result = update_device_price(raw_data, device_price_str, unit_dict_cookie, self.account_id)
                    self.result_status(result, unit_id)
                    time.sleep(random.randint(1, 3))
                    continue

            except Exception as e:
                error_msg = f"❌ 单元ID {unit_id} 出现异常: {str(e)}"
                self.log_message(error_msg, "red")
                time.sleep(3)

        self.status_label.config(text="✔️ 所有任务已完成", foreground="green")

    def result_status(self, result, unit_id, text_str=None):
        if result.get('code') == 200:
            self.log_message(f"✅ 单元ID {unit_id} - {text_str} 提交成功 - {result.get('text')} \n", "green")
        else:
            self.log_message(f"❌ 单元ID {unit_id} 提交失败: {result.get('msg', '未知错误')} \n", "red")

    def log_message(self, message, color="black"):
        self.log_text.config(state=tk.NORMAL)
        self.log_text.insert(tk.END, message + "\n", color)
        self.log_text.tag_config(color, foreground=color)
        self.log_text.config(state=tk.DISABLED)
        self.log_text.see(tk.END)

